import React, { useEffect, useRef, useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

export default function LoginR() {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const [imageUrl, setImageUrl] = useState('');
  let nav=useNavigate()
  // 获取摄像头流并在视频元素中显示
  const startCamera = () => {
    navigator.mediaDevices.getUserMedia({ video: true })
      .then(stream => {
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
        }
      })
      .catch(error => console.error('Error accessing camera:', error));
  };
  useEffect(() => {
    startCamera()
  },[])

  // 拍摄照片并将图像转换为Base64格式
  const takePicture = async() => {
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current;
      const canvas = canvasRef.current;

      // 设置canvas的尺寸与视频流一致
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      // 将视频帧绘制到canvas
      const context = canvas.getContext('2d');
      context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);

      // 获取canvas中的图像数据并转换为Base64格式
      const imageDataUrl = canvas.toDataURL('image/jpeg');
      setImageUrl(imageDataUrl);
    }
  };
  useEffect(() => {
    if (imageUrl !== '') {
      handleImageSubmit()
    }
  },[imageUrl])

  // 将Base64格式的图片发送到后端
  const handleImageSubmit = async () => {
    try {
      // 向后端发送Base64编码的图像数据
      const response = await axios.post('http://localhost:3000/zjj/faceLogin', { b64: imageUrl });
      if (response.data.code === 200) {
        sessionStorage.setItem('token', response.data.accessToken)
        sessionStorage.setItem('refToken', response.data.refToken)
            sessionStorage.setItem('_id',response.data._id)
            sessionStorage.setItem('tel',response.data.tel)
        
        nav('/jjthome')
      }
      console.log(response.data.msg);
      // 处理后端返回的消息
      // setMessage(response.data.message);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  return (
    <div className='login'>
      <h1>您好</h1>
          <div>
           <div className='shot'>
        <video ref={videoRef} autoPlay muted style={{ borderRadius:'50px',margin:'0 15%',width:'70%',height:'200px', maxWidth: '400px' }} />
        {/* <button onClick={startCamera}>打开摄像头</button>
        <button onClick={takePicture}>拍摄照片</button> */}
        <canvas ref={canvasRef} style={{ display: 'none' }} />
        </div>
        { (
            <div className='imgs'>
              {/* <img src={imageUrl} alt="Captured" /> */}
              <button onClick={takePicture}>登录</button>
            </div>
          )}
          </div>
          <p className='footer'>还没有账号？<span onClick={()=>{nav('/register')}}>去注册</span></p>      
    </div>
  )
}
